<!-- 供应商管理-供应商初选列表-新增供应商 -->
<template>
  <div class="supplier-add">
    <div>
      <div class="base-info">
        <h2>基本信息</h2>

        <a-form :model="form.list" class="aaa" auto-label-width>
          <a-form-item>
            <UploadFile
              ref="FileRef"
              v-model:file-list="headFile"
              listType="picture-card"
              class="avatar"
              :limit="1"
              :isShowRemove="type === 'add' || type === 'edit'"
            ></UploadFile>
          </a-form-item>
        </a-form>

        <div class="base-info-header">
          <a-form
            auto-label-width
            :model="form.list"
            :rules="rules"
            layout="vertical"
          >
            <a-form-item field="name" label="供应商名称：">
              <a-input
                placeholder="请输入供应商名称"
                :style="{
                  width: '100%',
                }"
                :disabled="type !== 'add' && type !== 'edit'"
                v-model="form.list.name"
                size="large"
              />
            </a-form-item>
          </a-form>
          <a-form :model="form.list" :rules="rules">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="number" label="供应商编号：">
                  <a-input
                    placeholder="请输入供应商编号"
                    size="large"
                    v-model="form.list.number"
                    :disabled="type !== 'add' && type !== 'edit'"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="level" label="供应商级别：">
                  <!-- <a-select
                    placeholder="请选择供应商级别"
                    v-model="supLevelName"
                    :disabled="type !== 'add' && type !== 'edit'"
                  >
                    <a-option>123</a-option>
                  </a-select> -->
                  <a-input v-model="supLevelName" disabled></a-input>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="supPhone" label="联系电话：">
                  <a-input
                    placeholder="请输入联系电话"
                    size="large"
                    :disabled="type !== 'add' && type !== 'edit'"
                    v-model="form.list.supPhone"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="detailedAddress" label="联系地址：">
                  <a-input
                    class="address"
                    placeholder="请输入联系地址"
                    size="large"
                    v-model="form.list.detailedAddress"
                    :disabled="type !== 'add' && type !== 'edit'"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="province" label="省市区：">
                  <a-input
                    placeholder="请输入省市区"
                    size="large"
                    :disabled="type !== 'add' && type !== 'edit'"
                    v-model="form.list.province"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="supEmail" label="联系邮箱：">
                  <a-input
                    placeholder="请输入联系邮箱"
                    size="large"
                    :disabled="type !== 'add' && type !== 'edit'"
                    v-model="form.list.supEmail"
                  />
                </a-form-item>

                <!-- <icon-location
                  :style="{
                    position: 'absolute',
                    fontSize: '32px',
                    color: '#5a9cf8',
                    cursor: 'pointer',
                  }"
                /> -->
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="supCategoryId" label="供应商类别：">
                  <a-select
                    placeholder="请选择供应商类别"
                    v-model="form.list.supCategoryId"
                    :disabled="type !== 'add' && type !== 'edit'"
                    @change="selectCategory"
                  >
                    <a-option
                      v-for="item in categoryList.list"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="supCommodityCategory"
                  label="供应商商品类别："
                >
                  <a-select
                    placeholder="供应商商品类别"
                    v-model="form.list.supCommodityCategory"
                    :disabled="type !== 'add' && type !== 'edit'"
                    multiple
                  >
                    <a-option
                      v-for="item in subCategoryList.list"
                      :key="item.id"
                      :label="item.details"
                      :value="item.details"
                    ></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item
                  field="supPerformanceRatingId"
                  label="供应商绩效评级："
                >
                  <a-select
                    placeholder="请选择供应商绩效评级："
                    v-model="form.list.supPerformanceRatingId"
                    :disabled="type !== 'add' && type !== 'edit'"
                  >
                    <a-option
                      v-for="item in rateList.list"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="industry" label="供应商领域：">
                  <a-input
                    placeholder="请输入领域名称"
                    size="large"
                    v-model="form.list.industry"
                    :disabled="type !== 'add' && type !== 'edit'"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-form
            auto-label-width
            :model="form.list"
            layout="vertical"
            class="serve-table"
          >
            <div
              :style="{
                border: '1px solid #f5f5f5',
              }"
            >
              <a-form-item field="name" label="可提供的产品：">
                <a-table
                  bordered
                  stripe
                  :style="{
                    width: '100%',
                  }"
                  :data="form.list.product"
                  :pagination="false"
                >
                  <template #columns>
                    <a-table-column :width="80" align="center">
                      <template #title> 序号 </template>
                      <template #cell="{ rowIndex }">
                        {{ rowIndex + 1 }}
                      </template>
                    </a-table-column>
                    <a-table-column title="产品明细">
                      <a-table-column
                        title="物料类型"
                        data-index="materialName"
                        align="center"
                        :width="100"
                      >
                      </a-table-column>
                      <a-table-column
                        title="物料编码"
                        data-index="number"
                        align="center"
                        :width="100"
                      >
                      </a-table-column>
                      <a-table-column
                        title="物料名称"
                        data-index="name"
                        align="center"
                        :width="100"
                      >
                      </a-table-column>
                      <a-table-column
                        title="规格型号"
                        data-index="spec"
                        align="center"
                        :width="100"
                      >
                      </a-table-column>
                    </a-table-column>
                  </template>
                </a-table>
              </a-form-item>
            </div>
          </a-form>
        </div>
        <div class="base-info-extra">
          <a-form :model="form.list" :rules="rules" auto-label-width>
            <h3>联系人信息</h3>
            <div class="contact-info">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="contactName" label="联系人姓名：">
                    <a-input
                      placeholder="请输入联系人姓名"
                      size="large"
                      v-model="form.list.contactMan[0].name"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="contactPhone" label="联系人电话：">
                    <a-input
                      placeholder="请输入联系人电话"
                      size="large"
                      v-model="form.list.contactMan[0].phone"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="contactPosition" label="联系人职位：">
                    <a-input
                      placeholder="请输入联系人职位"
                      size="large"
                      v-model="form.list.contactMan[0].job"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="contactDepartment" label="联系人部门：">
                    <a-input
                      placeholder="请输入联系人部门"
                      size="large"
                      v-model="form.list.contactMan[0].department"
                      :disabled="type !== 'add'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>

            <h3>客户账号信息</h3>
            <div class="client-info">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="accountName" label="账户名称：">
                    <a-input
                      placeholder="请输入账户名称"
                      size="large"
                      v-model="form.list.customerAccount[0].name"
                      :disabled="type !== 'add' && type !== 'edit'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="accountNumber" label="银行账号：">
                    <a-input
                      placeholder="请输入银行账号"
                      size="large"
                      v-model="form.list.customerAccount[0].account"
                      :disabled="type !== 'add' && type !== 'edit'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="accountCity" label="开户省市：">
                    <a-input
                      placeholder="请输入开户省市"
                      size="large"
                      v-model="form.list.customerAccount[0].bankOfProvince"
                      :disabled="type !== 'add' && type !== 'edit'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="accountBank" label="开户银行：">
                    <a-input
                      placeholder="请输入开户银行"
                      size="large"
                      v-model="form.list.customerAccount[0].bankOfDeposit"
                      :disabled="type !== 'add' && type !== 'edit'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
            <h3>备注信息</h3>
            <div class="remarks-info">
              <a-row :gutter="16">
                <a-col :span="24">
                  <a-form-item>
                    <a-textarea
                      placeholder=""
                      show-word-limit
                      :max-length="300"
                      allow-clear
                      :auto-size="{
                        minRows: 5,
                      }"
                      v-model="form.list.description"
                      :disabled="type !== 'add' && type !== 'edit'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-form>
        </div>
        <Enterprise ref="enterpriseRef" :form="enterpriseForm"></Enterprise>
        <div style="width: 100%; margin: 20px 50px">
          <a-space :size="20" direction="vertical" fill>
            <div>所需附件：</div>
            <div v-for="(element, index) in fileListAll" :key="index">
              <a-space direction="vertical" fill>
                <div>
                  <div class="uploadFile">
                    <span>{{ element.name }} </span>
                    <a :href="element.fileAddr" :download="element.name"
                      >下载</a
                    ></div
                  >
                </div>
              </a-space>
            </div>
            <div style="display: flex">
              <div>
                <span>支持pdf、doc、docx、wps文件格式，大小不超过20MB</span>
              </div>
            </div>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watchEffect } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { GetArchivesDetaliType } from '@/api/buy-management/archives-details/index';
  import {
    GetSupplierCategoryInfo,
    GetSupplierRateInfo,
    GetSupplierLevelInfo,
    GetSupplierTemplateDetailInfo,
  } from '@/api/buy-management/supplier-management/base-setting';
  import { openChoiceFile } from '@/utils/file';
  import { FileUpload } from '@/utils/upload';
  import { FileDownload } from '@/utils/filedownload';

  const router = useRouter();
  const route = useRoute();
  const type = computed(() => route.query.type); // 判断是新增客户还是看客户的基本信息
  const supLevelId = computed(() => Number(route.query.supLevelId)); // 模板id

  const uploadFileShow = ref(false);

  let file = ref(); // 储存头像
  let headPortraitFormData = new FormData();
  const form = reactive<any>({
    list: {
      number: '', // 供应商编号编号
      name: '', // 供应商名称
      creditCode: '', // 信用代码
      supCategoryId: undefined, // 供应商类别id
      supCommodityCategory: [], // 供应商商品类别id
      supLevelId: 0, // 供应商级别id
      supPerformanceRatingId: '', // 供应商绩效评级id
      supPhone: '', // 供应商联系电话
      supEmail: '', // 供应商联系邮箱
      province: '', // 所属省市
      detailedAddress: '', // 详细地址
      createUserId: 1, // 创建人id
      description: '', // 备注信息
      templateId: 1, // 模板id
      state: 1, // 状态
      extend: '', // 拓展
      industry: '', // 行业
      contactMan: [
        {
          name: '',
          phone: '',
          department: '',
          job: '',
        },
      ],
      customerAccount: [
        {
          name: '',
          account: '',
          bankOfDeposit: '', // 开户银行
          bankOfProvince: '', // 开户省市
        },
      ],
      product: [],
      serve: [
        {
          name: '',
          des: '',
        },
      ],
      file: [],
    },
  });

  let enterpriseForm = ref({
    businessLicense: '', // 营业执照
    creditCode: '', // 统一社会信用代码
    enterpriseName: '', // 企业名称
    legalRepresentative: '', // 法定代表人
    registrationStatus: '', // 登记状态
    establishmentDate: undefined, // 成立日期
    registeredCapital: '', // 注册资本
    paidCapital: '', // 实缴资本
    approvalDate: undefined, // 核准日期
    organizationCode: '', // 组织机构代码
    businessNo: undefined, // 工商注册号
    taxpayerNo: undefined, // 纳税人号
    enterpriseType: '', // 企业类型
    operationTerm: '', // 营业期限
    taxpayerQualification: '', // 纳税人资质
    industrySector: '', // 所属行业
    localArea: '', // 所属地区
    registrationAuthority: '', // 登记机关
    personnelSize: '', // 人员规模
    insuredPeople: undefined, // 参保人数
    formerName: '', // 曾用名
    englishName: '', // 英文名
    enterpriseCode: '', // 进出口企业代码
    registeredAddress: '', // 注册地址
    mainBusiness: '', // 主要经营
    opinion: '', //审批意见
    file: [],
  });

  let enterpriseRef = ref(); // 储存enterprise的ref

  const rules = reactive({
    name: [{ required: true, message: '请输入供应商名称' }],
    number: [{ required: true, message: '请输入供应商编号' }],
    level: [{ required: true, message: '请选择供应商级别' }],
    supPhone: [{ required: true, message: '请输入联系电话' }],
    detailedAddress: [{ required: true, message: '请输入联系地址' }],
    province: [{ required: true, message: '请输入省市区' }],
  });

  const requiredList = reactive<any>({
    list: [],
  });

  let supLevelName = ref(''); // 储存级别名称

  const ArchivesDetaliType = async () => {
    const res = await GetArchivesDetaliType({
      id: Number(route.query.id),
      typeId: 1,
    });
    form.list = res;

    enterpriseForm.value = JSON.parse(form.list.extend);
    const enterpriseFile =
      form.list.file?.find((item) => item.supplierFileType === 2) || {};

    enterpriseForm.value.file[0] = {
      fileAddr: enterpriseFile.addr,
      name: enterpriseFile.name,
    };

    // enterpriseForm.value = JSON.parse(res.extend);
  };
  ArchivesDetaliType();

  // 储存供应商类别数据
  const categoryList = reactive<any>({
    list: [],
  });

  // 储存供应商商品类别数据
  const subCategoryList = reactive<any>({
    list: [],
  });

  // 获取供应商类别数据
  const getSupplierCategoryInfo = async () => {
    try {
      const { data } = await GetSupplierCategoryInfo();
      categoryList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getSupplierCategoryInfo();

  // 储存供应商级别数据
  const rateList = reactive<any>({
    list: [],
  });
  // 获取供应商绩效评级数据
  const getSupplierRateInfo = async () => {
    try {
      const { data } = await GetSupplierRateInfo();
      rateList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getSupplierRateInfo();

  // 根据供应商类别id获取对应商品类别数据
  const selectCategory = (id: number) => {
    for (let i of categoryList.list) {
      if (i.id === id) {
        subCategoryList.list = i.child;
        break;
      }
    }
  };

  let isEdit = ref(false); // 判断用户是否点击编辑按钮
  const isEditBtn = () => {
    isEdit.value = !isEdit.value;
  };

  // 上传头像事件
  const onChange = (fileList: any, currentFile: any) => {
    file.value = {
      ...currentFile,
      url: URL.createObjectURL(currentFile.file),
    };
    headPortraitFormData.append('headPortrait', currentFile.file);
  };
  const onProgress = (currentFile: any) => {
    file.value = currentFile;
  };

  // 新增产品明细
  const addProduction = (index: number) => {
    const item = {
      number: '',
      name: '',
      model: '',
      spec: '',
      des: '',
      type: '',
    };
    form.list.product.splice(index + 1, 0, item);
  };

  // 新增产品明细
  const addServe = (index: number) => {
    const item = {
      name: '',
      des: '',
    };
    form.list.serve.splice(index + 1, 0, item);
  };

  let headFile = computed({
    get() {
      return form.list.file.filter((i) => i.supplierFileType === 1).length >
        0 && form.list.file.filter((i) => i.supplierFileType === 1)[0].addr
        ? [
            {
              fileUrl: form.list.file[0].addr,
              fileName: form.list.file[0].name,
            },
          ]
        : [];
      // return [];
    },
    set(val: any[]) {
      if (val[0])
        form.list.file.push({
          addr: val[0].sourceAddr,
          name: val[0].fileName,
          fileType: 1,
          supplierFileType: 1,
        });
    },
  });

  const fileListAll = computed(() => {
    return form.list.file.filter((i) => i.supplierFileType === 3);
  });

  const Supplierproducts = ref();
  const addSmpleDetails = async (titleData: any) => {
    let data = {
      product: [],
    };
    titleData.map((item: any) => {
      data.product.push(item);
      return data.product;
    });
    form.list.product = data.product;
    Supplierproducts.value = titleData;
  };

  const deleteItem = (data: any, key: any) => {
    Supplierproducts.value.splice(key, 1);
  };

  const addFile = () => {
    form.list.file.push({});
  };

  const upload = async (Uindex) => {
    let file = new FormData();
    form.file = await openChoiceFile(
      ['.mp4', '.pdf', '.png', '.txt', '.jpg', '.docx'],
      1024 * 1024 * 10
    );
    file.append('data', form.file);
    const res = await FileUpload(file);
    form.list.file.forEach((item, index) => {
      if (Uindex === index) {
        item.name = res.data.data.name;
        item.addr = res.data.data.sourceAddr;
        uploadFileShow.value = true;
      }
    });
  };
</script>

<style scoped lang="less">
  .supplier-add {
    .base-info {
      padding: 10px 60px 10px 20px;

      .aaa {
        position: absolute;

        :deep(.arco-form-item-label-required-symbol) {
          position: absolute;
          top: 0;
          left: 0;
        }
      }
      .avatar {
        position: absolute;
        top: 0;
        left: 0;
      }
      &-header {
        padding: 0 100px;
        :deep(.arco-form-item-content-flex) {
          display: block;
          line-height: 32px;
          color: #cccccc29;
        }
      }

      &-extra {
        .contact-info,
        .invoice-info,
        .client-info,
        .remarks-info {
          padding: 0 100px;
        }
      }
      :deep(.arco-input-wrapper .arco-input[disabled]),
      :deep(.arco-select-view-single.arco-select-view-disabled),
      :deep(.arco-select-view-multiple.arco-select-view-disabled
          .arco-select-view-tag) {
        // -webkit-text-fill-color: #165dff;
      }
    }
  }

  .uploadFile {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    box-sizing: border-box;
    width: 40%;
    padding: 8px 10px 8px 12px;
    overflow: hidden;
    font-size: 14px;
    background-color: var(--color-fill-1);
    border-radius: var(--border-radius-small);
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
    margin-top: 10px;
  }
</style>
